package sealte.mynode.bean;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import sealte.mynode.pojo.User;
import sealte.mynode.db.DBConnection;

/**
 * USER Bean
 * @author SEALTE
 * 2012-11-14
 */
public class UserBean {
	private Connection conn = null;
	private PreparedStatement ps = null;
	private ResultSet rs = null;
	
	public boolean addNew(User user){
		String sql = "INSERT INTO M_USER(F_NAME,F_PASSWORD,F_EMAIL,F_JOINTIME,F_ONLINE) VALUES(?,MD5(?),?,?,?)";
		try{
			conn = DBConnection.getConnection();
			ps = conn.prepareStatement(sql);
			ps.setString(1, user.getName());
			ps.setString(2, user.getPassword());
			ps.setString(3, user.getEmail());
			ps.setString(4, user.getJoinTime());
			ps.setString(5, user.getOnline());
			ps.execute();
			return true;
		}catch(Exception e){
			e.printStackTrace();
			return false;
		}finally{
			DBConnection.close(null, ps, conn);
		}
	}
	
	public User login(String name,String password){
		User user = null;
		String sql = "SELECT F_ID,F_EMAIL,F_JOINTIME,F_OUTTIME FROM M_USER WHERE F_NAME=? AND F_PASSWORD=MD5(?)";
		try{
			conn = DBConnection.getConnection();
			ps = conn.prepareStatement(sql);
			ps.setString(1, name);
			ps.setString(2, password);
			rs = ps.executeQuery();
			if(rs.next()){
				user = new User();
				int id = rs.getInt("F_ID");
				user.setId(id);
				user.setName(name);
				user.setEmail(rs.getString("F_EMAIL"));
				user.setJoinTime(rs.getString("F_JOINTIME"));
				user.setOutTime(rs.getString("F_OUTTIME"));
				sql = "UPDATE M_USER SET F_ONLINE=? WHERE F_ID=?";
				ps = conn.prepareStatement(sql);
				ps.setString(1, "Y");
				ps.setInt(2, id);
				ps.execute();
				return user;
			}else{
				return null;
			}
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}finally{
			DBConnection.close(rs, ps, conn);
		}
	}
	
	public boolean logout(int id,String outTime){
		String sql = "UPDATE M_USER SET F_ONLINE='N',F_OUTTIME=? WHERE F_ID=?";
		try{
			conn = DBConnection.getConnection();
			ps = conn.prepareStatement(sql);
			ps.setString(1, outTime);
			ps.setInt(2, id);
			ps.execute();
			return true;
		}catch(Exception e){
			e.printStackTrace();
			return false;
		}finally{
			DBConnection.close(null, ps, conn);
		}
	}
	
	
}
